package com.opencart.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.opencart.dao.CategoryDAO;
import com.opencart.dao.utils.OpenCartHibernateDaoSupport;
import com.opencart.domain.Category;
import com.opencart.utils.web.pagination.PagedResultSet;
import com.opencart.utils.web.pagination.Pager;

@Repository("categoryDAO")
public class CategoryDAOImpl extends OpenCartHibernateDaoSupport implements
		CategoryDAO {

	public Category findById(Long id) {
		return this.getHibernateTemplate().get(Category.class, id);
	}

	public Category saveOrUpdate(Category category) {
		this.getHibernateTemplate().saveOrUpdate(category);
		return category;
	}

	public PagedResultSet paginate(Pager pager) {
		List<Category> pagedResultSet = this.findAll(pager);
		PagedResultSet pr = new PagedResultSet();
		pr.setPager(pager);
		pr.setResultSet(pagedResultSet);
		pr.setRowCount(this.getAllCount());
		return pr;
	}

	@SuppressWarnings("unchecked")
	public List<Category> findAll(Pager pager) {
		StringBuilder sb = new StringBuilder();
		sb.append("select obj from").append(" ")
				.append(Category.class.getName()).append(" ").append("obj")
				.append(" ");
		if (pager.getSortOrder() == "asc") {
			sb.append("order by").append(" ").append(pager.getSortColumn())
					.append(" ").append("asc").append(" ");
		} else {
			sb.append("order by").append(" ").append(pager.getSortColumn())
					.append(" ").append("desc").append(" ");
		}
		Query query = this.getSession().createQuery(sb.toString())
				.setFirstResult(pager.getPage() - 1)
				.setMaxResults(pager.getPageSize());
		Object pagedResultSet = query.list();
		if (pagedResultSet != null && pagedResultSet instanceof List<?>) {
			return (List<Category>) pagedResultSet;
		} else {
			return new ArrayList<Category>();
		}
	}

	public Integer getAllCount() {
		Long cnt = (Long) this
				.getSession()
				.createQuery(
						"select count(obj.id) from " + Category.class.getName()
								+ " obj").uniqueResult();
		int count = cnt.intValue();
		return count;
	}

	@SuppressWarnings("unchecked")
	public List<Category> findAll() {
		Object list = getHibernateTemplate().find(
				"select obj from com.opencart.domain.Category obj");
		if (list != null && list instanceof List<?>) {
			return (List<Category>) list;
		} else {
			return new ArrayList<Category>();
		}
	}

	public void delete(Category category) {
		this.getHibernateTemplate().delete(category);
	}

}
